import { Button, Form, Image, Input, Popup, Toast } from '@nutui/nutui-react';
import { useCountDown, useRequest } from 'ahooks';
import { useState } from 'react';

import { commonApi } from '@/application/apis/home';
import { useUser } from '@/application/hooks/use-user';
import img_close from '@/public/images/close.png';
import { UserLoginParams } from '@/types/user';

import { useHome } from '../context';

export const TIPS: Record<string, string> = {
  phoneNum: '请输入正确的手机号'
};
export const VERIFY_DICT: Record<string, (value: string, tips?: string) => boolean> = {
  phone: (val, tips) => {
    if (
      !val ||
      val?.trim?.().length === 0 ||
      !/^1(?!70|71|62|67|65|2\d)[0-9]{10}$/g.test(val?.trim?.())
    ) {
      tips && Toast.show(tips);
      return false;
    }
    return true;
  }
};

const Captcha = ({ value, onChange, getCaptcha }: any) => {
  const [msg, setMsg] = useState('获取验证码');
  const [targetDate, setTargetDate] = useState<number>();

  const [countdown] = useCountDown({
    targetDate,
    onEnd: () => {
      setMsg('重新获取');
    }
  });
  const getCaptchaAsync = async () => {
    try {
      await getCaptcha();
      setTargetDate(Date.now() + 60 * 1000);
      Toast.show('发送成功');
    } catch (e: any) {
      Toast.show(e.message);
    }
  };
  return (
    <div className="flex !h-12 items-center !bg-[#F7F7F7] !px-5 !text-base">
      <Input
        placeholder="请输入验证码"
        type="text"
        className="!bg-[#F7F7F7]"
        value={value}
        onChange={onChange}
        maxLength={4}
      />

      <div className="right">
        <Button fill="none" onClick={getCaptchaAsync} disabled={countdown !== 0}>
          {countdown !== 0 ? `${Math.round(countdown / 1000)}s` : msg}
        </Button>
      </div>
    </div>
  );
};
export function Login() {
  const [form] = Form.useForm();
  const { runAsync } = useRequest(commonApi.getSmsCode, {
    manual: true
  });
  const { showLogin, setShowLogin } = useHome();
  const { login } = useUser();
  const getCaptcha = async () => {
    const phoneKey = 'phone';
    const phone = form.getFieldValue(phoneKey);
    if (!VERIFY_DICT[phoneKey](phone, TIPS[phoneKey])) {
      throw new Error('请输入正确的手机号');
    }
    await runAsync({
      phone
    });
  };

  const submitSucceed = async () => {
    login && (await login());
    setShowLogin(false);
  };

  return (
    <Popup
      onClose={() => setShowLogin(false)}
      position="bottom"
      visible={showLogin}
      zIndex={100}
      className="relative !z-20 rounded-t-[19px] !bg-white "
      overlayClassName="!bg-transparent !z-[1]"
    >
      <div className="px-5.5 py-7">
        <div className="relative">
          <div className="text-center text-[20px] text-[#002040]">请输入账号登录</div>
          <div
            className="absolute bottom-0 right-0 top-0 my-auto h-4 w-4"
            onClick={() => setShowLogin(false)}
          >
            <Image src={img_close} />
          </div>
        </div>
        <div className="pt-[20px] text-[11px] text-black-2">
          仅支持中国大陆内11位(+86)手机号码，该号码后续可查询订单，请确保所填写号码无误
        </div>
        <Form
          form={form}
          footer={
            <>
              <Button nativeType="submit" block type="primary">
                立即登录
              </Button>
            </>
          }
          onFinish={() => submitSucceed()}
        >
          <Form.Item
            name="name"
            rules={[
              {
                required: true,
                message: '请填写真实姓名，否则无法兑换礼品'
              }
            ]}
          >
            <Input
              className="!h-12 !bg-[#F7F7F7] !px-5 !text-base"
              placeholder="请填写真实姓名，否则无法兑换礼品"
              type="text"
            />
          </Form.Item>
          <Form.Item
            name="phone"
            rules={[
              {
                required: true,
                pattern: /^1(?!70|71|62|67|65|2\d)[0-9]{10}$/,
                message: '请输入正确的手机号'
              }
            ]}
          >
            <Input
              className="!h-12 !bg-[#F7F7F7] !px-5 !text-base"
              placeholder="请输入手机号"
              type="number"
            />
          </Form.Item>
          <Form.Item name="captcha" rules={[{ required: true, message: '请输入验证码' }]}>
            <Captcha getCaptcha={getCaptcha} />
          </Form.Item>
        </Form>
      </div>
    </Popup>
  );
}
